package fe.bmsearch.gui.server;

import java.util.ArrayList;
import java.util.List;

import javax.management.RuntimeErrorException;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import fe.bmsearch.gui.client.BMIndexedSearchService;
import fe.bmsearch.gui.client.SearchResultItem;
import fe.datatypeUI.ShortDescription;
import fe.documentquery.PathToSelector;
import fe.documentquery.Query;
import fe.generalmodel.DataType;
import fe.generalmodel.Selector;
import fe.hbasequery.QueryIndex;
import fe.utils.UniqueStringUtils;

public class BMIndexedSearchServiceImpl extends RemoteServiceServlet
 implements BMIndexedSearchService {

	private static final long serialVersionUID = 1L;
 
	public List<SearchResultItem> doSearch(String dataType, String pathJSON, String selector) {
		List<SearchResultItem> results=new ArrayList<SearchResultItem>();
		try
		{
			PathToSelector pts=PathToSelector.fromJSON(pathJSON);
			Selector s=PathToSelector.getSelectorType(pts).getConstructor(String.class).newInstance(selector);
			Query q=new Query(pts, s, 200);
			for(DataType dt:QueryIndex.executeQuery(q))
			{
				results.add(new SearchResultItem(dataType, UniqueStringUtils.bytesToHex(dt.getUid()), ShortDescription.getShortDescription(dt)));
			}
		} catch(Exception e)
		{
			results.add(new SearchResultItem("", "en fejl","sdf"));
			throw new RuntimeException("Failed to query hbase");
		}
		if(results.size()==0)
		{
			results.add(new SearchResultItem("", "", "No matching results"));
		}
		return results;
	}

}
